import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Queue;
import java.util.TreeMap;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=103 lang=java
 *
 * [103] 二叉树的锯齿形层次遍历
 *
 * https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/description/
 *
 * algorithms
 * Medium (52.75%)
 * Likes:    125
 * Dislikes: 0
 * Total Accepted:    26.7K
 * Total Submissions: 50.5K
 * Testcase Example:  '[3,9,20,null,null,15,7]'
 *
 * 给定一个二叉树，返回其节点值的锯齿形层次遍历。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。
 *
 * 例如：
 * 给定二叉树 [3,9,20,null,null,15,7],
 *
 * ⁠   3
 * ⁠  / \
 * ⁠ 9  20
 * ⁠   /  \
 * ⁠  15   7
 *
 *
 * 返回锯齿形层次遍历如下：
 *
 * [
 * ⁠ [3],
 * ⁠ [20,9],
 * ⁠ [15,7]
 * ]
 *
 *
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if(root == null) return new ArrayList<>();
        List<List<Integer>> list = new ArrayList<>();
        boolean flag = true;
        Deque<TreeNode> q = new ArrayDeque<>();
        q.add(root);
        while(!q.isEmpty()) {
            if(flag) {
                List<Integer> l = new ArrayList<>();
                for(int i=q.size(); i > 0; i--) {
                    TreeNode t = q.pollFirst();
                    l.add(t.val);

                    if(t.left != null) {
                        q.addLast(t.left);
                    }
                    if(t.right != null) {
                        q.addLast(t.right);
                    }
                }
                list.add(l);
            } else {
                List<Integer> l = new ArrayList<>();
                for(int i=q.size(); i > 0; i--) {
                    TreeNode t = q.pollLast();
                    l.add(t.val);
                    if(t.right != null) {
                        q.addFirst(t.right);
                    }
                    if(t.left != null) {
                        q.addFirst(t.left);
                    }

                }
                list.add(l);
            }
            flag = !flag;
        }
        return list;
    }
}
// @lc code=end

